<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useNoticeStore } from "@/store/notice";
import { useMyToastStore } from "@/store/myToast";

const myToast = useMyToastStore();
const notice = useNoticeStore();
const instance = getCurrentInstance();
const util = instance?.proxy?.$util;
const request = instance?.proxy?.$request;

let userInfo = reactive({
  data: {},
});
if (!uni.getStorageSync("userInfo")) {
  util.jumpPage("/pages/user/login");
}
// 日期相关
let showTodayCourse = ref(false);
let todayCourse = reactive({
  morning: [],
  afternoon: [],
  night: [],
});
let week = ref(0);
let todayDate = uni.$u.timeFormat(Number(new Date()), "yyyy/mm/dd");
let todayWeek = ref("");
// 最新消息
let newNotice = reactive([]);

onShow(async () => {
  if (uni.getStorageSync("userInfo")) {
    userInfo.data = uni.getStorageSync("userInfo");
  }
  // 今日课表
  if (uni.getStorageSync("courseList")) {
    showTodayCourse.value = uni.getStorageSync("showTodayCourse");
    //获取开学时间
    const startDate = uni.getStorageSync("startDate")
      ? uni.getStorageSync("startDate")
      : todayDate;
    // 获取课表
    const courseList = uni.getStorageSync("courseList");
    week.value = util.getWeek(
      uni.$u.timeFormat(Number(new Date()), "yyyy/mm/dd"),
      startDate
    );
    let weekCourse = courseList[week.value - 1];
    let today = new Date().getDay();
    if (today == 0) {
      today = 7;
    }
    let obj = {
      1: "一",
      2: "二",
      3: "三",
      4: "四",
      5: "五",
      6: "六",
      7: "日",
    };
    todayWeek.value = obj[today];
    todayCourse = {
      morning: [],
      afternoon: [],
      night: [],
    };
    weekCourse.forEach((item) => {
      if (item.xqj == today) {
        if (item.jcs[1] <= 5) {
          todayCourse.morning.push(item);
        } else if (item.jcs[1] > 5 && item.jcs[1] <= 9) {
          todayCourse.afternoon.push(item);
        } else {
          todayCourse.night.push(item);
        }
      }
    });
  }
  // 延时请求下一次消息列表
  if (notice.isNext && uni.getStorageSync("userInfo")) {
    getNoticeList();
    notice.isNext = false;
    setTimeout(() => {
      notice.isNext = true;
    }, 180000);
  }
});
// 最新消息
const getNoticeList = async () => {
  let todayDate = uni.$u.timeFormat(Number(new Date()), "yyyy/mm/dd");
  let newLoginDate = uni.getStorageSync("newLoginDate") || "";
  if (
    (uni.getStorageSync("loginExpired") ?? true) &&
    todayDate == newLoginDate
  ) {
    try {
      const { data } = await request.post("noticeList", {
        cookie: userInfo.data.cookie,
        page: 1,
        type: 1,
      });
      console.log(data);
      // 获取消息相差天数
      let todayDate = new Date();
      data.items.forEach((item) => {
        let noticeDate = new Date(item.cjsj.replaceAll("-", "/"));
        let day = parseInt((todayDate - noticeDate) / (1000 * 60 * 60 * 24));
        if (day < 7) {
          newNotice.push(item.cjsj + "，" + item.xxnr);
          item.isLately = true;
        }
        item.xxnr = item.xxnr.split(":");
      });
      notice.data = data.items;
    } catch (error) {
      console.log(error);
    }
  }
};
uni.$on("updateLoginInfo", () => {
  userInfo.data = uni.getStorageSync("userInfo");
  getNoticeList();
});
// 退出登录
let isRemember = ref(false);
const handleLoginAgain = () => {
  isRemember.value = uni.getStorageSync("isRemember") ?? false;
  if (uni.getStorageSync("userInfo")) {
    if (isRemember.value) {
      util.jumpPage("/pages/user/login");
    } else {
      uni.showModal({
        title: "退出登录？",
        content: "这将会清除您的登录信息",
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync("userInfo");
            userInfo.data = {};
            newNotice = [];
            util.jumpPage("/pages/user/login");
          }
        },
      });
    }
  } else {
    util.jumpPage("/pages/user/login");
  }
};
let list = reactive([
  {
    name: "我的课表",
    src: "/static/index/kebiao.png",
    page: "/pages/index/courseList",
  },
  {
    name: "消息列表",
    src: "/static/index/notice.png",
    page: "/pages/index/noticeList",
  },
  {
    name: "成绩查询",
    src: "/static/index/chengji.png",
    page: "/pages/index/scoresList",
  },
]);
const handleGridClick = async (e, i) => {
  if ((i == 1 || i == 2) && !uni.getStorageSync("userInfo")) {
    myToast.params = {
      type: "error",
      message: "请先登录",
    };
    return;
  }
  if (!uni.getStorageSync("userInfo") && !uni.getStorageSync("courseList")) {
    myToast.params = {
      type: "error",
      message: "请先登录",
    };
    return;
  }
  util.jumpPage(e);
};
</script>
<script>
export default {
  // 分享
  onShareAppMessage() {
    return {
      title: "让我看看是谁要上早八？",
      path: "/pages/index/index",
      imageUrl: "/static/logo-5:4.png",
    };
  },
};
</script>

<template>
  <view class="index">
    <myToast></myToast>
    <u-navbar
      :placeholder="true"
      bgColor="#f1fffa"
      leftIconSize="48"
      leftIcon="file-text"
      leftIconColor="#666"
      @leftClick="util.jumpPage('/pages/index/updateLog')"
    >
      <template #center>
        <text class="text-16 text-bold-700">早八日常</text>
      </template>
    </u-navbar>
    <view class="index-content">
      <view class="notice-box" v-if="newNotice.length > 0">
        <u-notice-bar
          fontSize="26"
          mode="link"
          bgColor="#10936318"
          color="#109363"
          duration="3000"
          url="/pages/index/noticeList"
          direction="column"
          :text="newNotice"
        ></u-notice-bar>
      </view>
      <view
        class="content-title flex justify-between"
        @click="handleLoginAgain"
      >
        <text
          >绑定信息：{{
            userInfo.data.account ? userInfo.data.account : "未登录"
          }}</text
        >
        <view class="login-again">{{
          userInfo.data.account ? "重新登录" : "立即登录"
        }}</view>
      </view>
      <view class="gird-box">
        <u-grid :border="false" col="3">
          <u-grid-item
            v-for="(listItem, listIndex) in list"
            :key="listIndex"
            @click="handleGridClick(listItem.page, listIndex)"
          >
            <image
              class="item-image"
              style="height: auto"
              :src="listItem.src"
              mode="widthFix"
            />
            <text class="item-text">{{ listItem.name }}</text>
          </u-grid-item>
        </u-grid>
      </view>
      <view class="today-course" v-if="showTodayCourse">
        <view class="course-title flex align-center justify-between">
          <view class="title-text">今日课表</view>
          <view class="title-right">
            <view class="date">
              <text>{{ todayDate.replaceAll("/", "-") }} </text>
            </view>
            <view class="week"> 第{{ week }}周 星期{{ todayWeek }} </view>
          </view>
        </view>
        <view
          class="course-item"
          @click="handleGridClick('/pages/index/courseList')"
        >
          <view class="course-item-title">
            <text>上午课程</text>
          </view>
          <view
            class="course-item-content flex"
            :class="todayCourse.morning.length == 0 ? 'item-null' : ''"
          >
            <view class="item-left flex flex-column justify-around">
              <view>08:00</view>
              <view class="circle-box flex align-center justify-center">
                <view class="circle-item"></view>
                <view class="circle-item"></view>
                <view class="circle-item"></view>
              </view>
              <view>12:00</view>
            </view>
            <view class="item-right flex-sub">
              <view
                class="item-right-item"
                :style="{ backgroundColor: item.bgColor }"
                v-for="(item, index) in todayCourse.morning"
                :key="index"
              >
                <view
                  class="line-icon"
                  :style="{ backgroundColor: item.bgColor }"
                ></view>
                <view class="course-name">
                  <text>{{ item.kcmc }}</text>
                  <text class="course-time ml-xxs">{{ item.xm }}</text>
                </view>
                <view class="course-time"
                  >第{{ item.jcs[0] }}节 - 第{{ item.jcs[1] }}节 @{{
                    item.cdmc
                  }}</view
                >
              </view>
              <view
                class="item-right-item"
                v-if="todayCourse.morning.length == 0"
                ><view class="line-icon"></view>
                <view class="course-name">空闲</view>
                <view class="course-time">第1节 - 第5节</view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="course-item"
          @click="handleGridClick('/pages/index/courseList')"
        >
          <view class="course-item-title">
            <text>下午课程</text>
          </view>
          <view
            class="course-item-content flex"
            :class="todayCourse.afternoon.length == 0 ? 'item-null' : ''"
          >
            <view class="item-left flex flex-column justify-around">
              <view>14:30</view>
              <view class="circle-box flex align-center justify-center">
                <view class="circle-item"></view>
                <view class="circle-item"></view>
                <view class="circle-item"></view>
              </view>
              <view>17:40</view>
            </view>
            <view class="item-right flex-sub">
              <view
                class="item-right-item"
                :style="{ backgroundColor: item.bgColor }"
                v-for="(item, index) in todayCourse.afternoon"
                :key="index"
              >
                <view
                  class="line-icon"
                  :style="{ backgroundColor: item.bgColor }"
                ></view>
                <view class="course-name">
                  <text>{{ item.kcmc }}</text>
                  <text class="course-time ml-xxs">{{ item.xm }}</text>
                </view>
                <view class="course-time"
                  >第{{ item.jcs[0] }}节 - 第{{ item.jcs[1] }}节 @{{
                    item.cdmc
                  }}</view
                >
              </view>
              <view
                class="item-right-item item-null"
                v-if="todayCourse.afternoon.length == 0"
                ><view class="line-icon"></view>
                <view class="course-name">空闲</view>
                <view class="course-time">第6节 - 第9节</view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="course-item"
          @click="handleGridClick('/pages/index/courseList')"
        >
          <view class="course-item-title">
            <text>晚上课程</text>
          </view>
          <view
            class="course-item-content flex"
            :class="todayCourse.night.length == 0 ? 'item-null' : ''"
          >
            <view class="item-left flex flex-column justify-around">
              <view>19:30</view>
              <view class="circle-box flex align-center justify-center">
                <view class="circle-item"></view>
                <view class="circle-item"></view>
                <view class="circle-item"></view>
              </view>
              <view>21:00</view>
            </view>
            <view class="item-right flex-sub">
              <view
                class="item-right-item"
                :style="{ backgroundColor: item.bgColor }"
                v-for="(item, index) in todayCourse.night"
                :key="index"
              >
                <view
                  class="line-icon"
                  :style="{ backgroundColor: item.bgColor }"
                ></view>
                <view class="course-name">
                  <text>{{ item.kcmc }}</text>
                  <text class="course-time ml-xxs">{{ item.xm }}</text>
                </view>
                <view class="course-time"
                  >第{{ item.jcs[0] }}节 - 第{{ item.jcs[1] }}节 @{{
                    item.cdmc
                  }}</view
                >
              </view>
              <view
                class="item-right-item item-null"
                v-if="todayCourse.night.length == 0"
                ><view class="line-icon"></view>
                <view class="course-name">空闲</view>
                <view class="course-time">第10节 - 第11节</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="bottom-text">- 海压竹枝低复举，风吹山角晦还明 -</view>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background: linear-gradient(#f1fffa, #f1fffa, #fff 28%) no-repeat;
}
.index {
  font-size: 28rpx;
  .index-content {
    padding: 28rpx 18rpx 44rpx;
    border-radius: 12px;
    .notice-box {
      padding: 16rpx 0;
      :deep(.u-icon__icon) {
        font-size: 18px !important;
      }
    }
    .content-title {
      margin-top: 36rpx;
      padding: 0 14rpx 36rpx;
      font-size: 28rpx;
      color: #606165;
      .login-again {
        padding: 8rpx 16rpx;
        background-color: #109363;
        border-radius: 8rpx;
        font-size: 24rpx;
        color: #fff;
      }
    }
    .gird-box {
      :deep(.u-grid-item) {
        padding: 0 32rpx;
        margin-top: 24px;
      }
      .item-text {
        text-align: center;
        color: #999;
        font-size: 28rpx;
        font-weight: 700;
      }
    }
    .today-course {
      margin-top: 48rpx;
      padding: 36rpx 14rpx 0;
      font-size: 12px;
      color: #606165;
      border-top: 1px solid #f0f0f0;
      .course-title {
        margin-bottom: 32rpx;
        .title-text {
          font-weight: 700;
          font-size: 36rpx;
        }
        .title-right {
          text-align: center;
        }
      }
      .course-item {
        margin-bottom: 28rpx;
        &-title {
          padding-bottom: 18rpx;
          font-size: 13px;
          text {
            color: #606165;
          }
        }
        &-content {
          .item-left {
            text-align: center;
            color: #606165;
            .circle-box {
              .circle-item {
                width: 4rpx;
                height: 4rpx;
                margin-left: 8rpx;
                opacity: 0.5;
                background-color: #606165;
                border-radius: 50%;
                &:first-child {
                  margin-left: 0;
                }
              }
            }
          }
          .item-right {
            margin-left: 48rpx;
            &-item {
              position: relative;
              padding: 12rpx 18rpx;
              margin-bottom: 24rpx;
              color: #fff;
              background-color: #10936399;
              border-radius: 12rpx;
              &:last-child {
                margin-bottom: 0;
              }
              .line-icon {
                display: block;
                position: absolute;
                left: -28rpx;
                top: 0;
                bottom: 0;
                width: 8rpx;
                border-radius: 8rpx;
                background-color: #10936399;
              }
              .course-name {
                font-size: 26rpx;
                margin-bottom: 4rpx;
              }
              .course-time {
                font-size: 12px;
                color: #ffffffcc;
              }
            }
          }
        }
        .item-null {
          .item-right-item {
            background-color: #f1f3f5 !important;
            color: #9198a3 !important;
            .line-icon {
              background-color: #eee !important;
            }
            .course-time {
              font-size: 12px;
              color: #9198a3 !important;
            }
          }
        }
      }
    }
    .slot-content {
      width: 100%;
      .item-input {
        padding-top: 24rpx;
        color: #333;
        .input-text {
          width: 128rpx;
          text-align: center;
        }
      }
    }
    .bottom-text {
      margin-top: 188rpx;
      text-align: center;
      font-size: 24rpx;
      color: #9198a3;
    }
    u-input {
      width: 100%;
    }
  }
}
</style>
